package com.example.demo.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.example.demo.entity.*;
import com.example.demo.pay.Alipay;
import com.example.demo.pay.PayContext;
import com.example.demo.pojo.BSResult;
import com.example.demo.service.BookInfoService;
import com.example.demo.service.CartService;
import com.example.demo.service.OrderDetailService;
import com.example.demo.service.OrderService;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.print.Book;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private BookInfoService bookInfoService;

    @Autowired
    private CartService cartService;


    @Autowired
    private OrderService orderService;


    @Autowired
    private Alipay alipay;

    @Autowired
    private OrderDetailService orderDetailService;

@RequestMapping("/info")
    public String orderInfo(
        @RequestParam(defaultValue = "0",required = false) Integer book_id,
        @RequestParam(defaultValue = "0",required = false) Integer buyNum,
        HttpServletRequest request, Model model){

        if(book_id!=0){
            BookInfo bookInfo=bookInfoService.findByBookId(book_id);
            if(bookInfo!=null){
                BSResult result=cartService.addToCart(bookInfo,null,buyNum);
                request.getSession().setAttribute("buyNowCart", result.getData());
                 //request ,not session!
                request.setAttribute("cart",result.getData());
            }else{
                request.setAttribute("exception", "不好意思，书籍库存不足或不存在了！");
                return "exception";
            }
        }
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        Cart buyNowCart=(Cart) request.getSession().getAttribute("buyNowCart");
        if ((cart != null && cart.getTotal() > 0)||(buyNowCart != null && buyNowCart.getTotal() > 0)  ) {
         return "order_info";
         } else {
        return "cart";
        }

    }

    @RequestMapping("/list")
    public String orderList(HttpServletRequest request,Model model){

        User user=(User)request.getSession().getAttribute("loginUser");
        List<OrderCustom> orderCustoms=orderService.findAllOrdersByUserId(user.getUserId());
        model.addAttribute("orderCustoms",orderCustoms);
        return "order_list";
    }


//dingdanjiesuan
    @RequestMapping("/creation")
    public String creation(Model model, User user,  String express, Integer payMethod,HttpServletRequest request){



        User loginUser=(User)request.getSession().getAttribute("loginUser");
        user.setUserId(loginUser.getUserId());
        user.setZipCode(loginUser.getZipCode());

        //buynowCart
        Cart buyNowCart=(Cart) request.getSession().getAttribute("buyNowCart");

        if(buyNowCart!=null){
            BSResult cartResult=orderService.createOrder(user,buyNowCart,express,payMethod);
            if(cartResult.getCode()==200){
                request.setAttribute("order",cartResult.getData());
                request.setAttribute("payMethod",payMethod);
                cartService.removeCart(request,"cart");
                return "payment";
            }
            else{
                request.setAttribute("exception","Failed!");
                return "exception";
            }

        }



        //normal cart
        Cart cart=(Cart) request.getSession().getAttribute("cart");

        if(cart!=null){
            BSResult cartResult=orderService.createOrder(user,cart,express,payMethod);
            if(cartResult.getCode()==200){
                request.setAttribute("order",cartResult.getData());
                request.setAttribute("payMethod",payMethod);
                cartService.removeCart(request,"cart");
                return "payment";
            }else{
                request.setAttribute("exception","Failed!");
                return "exception";
            }

        }


        return "payment";
    }



    @RequestMapping("/deletion/{orderId}")

    public String orderDeletion(@PathVariable(value = "orderId") String orderId,HttpServletRequest request){

        int i=orderService.deleteOrdersByOrderId(orderId);
        if(i==1){

            return "forward:/order/list";
        }else{
            request.setAttribute("exception","Failed!");
            return "exception";
        }
    }


    @RequestMapping("/payPage/{orderId}")
    public String toPay(@PathVariable("orderId") String orderId, Model model) {

        BSResult bsResult = orderService.findOrdersByOrderId(orderId);

        if (bsResult.getCode() == 200) {
            model.addAttribute("order", bsResult.getData());
            return "payment";
        }
        return "exception";
    }


    @RequestMapping(value = "/tradeQuery/{orderId}")
    public String tradeQuery(@PathVariable("orderId") String orderId, Model model, HttpServletResponse response,HttpServletRequest request) throws IOException, AlipayApiException {
        BSResult result=orderService.findOrdersByOrderId(orderId);
        Orders order= (Orders) result.getData();
        List<BookInfo> bookInfos=orderDetailService.findBookInfoByOrderId(orderId);
        PayContext payContext=new PayContext();
        payContext.setOrder(order);
        payContext.setBookInfos(bookInfos);
        payContext.setResponse(response);
        AlipayTradeQueryResponse queryResponse= alipay.tradeQuery(payContext,request);
        model.addAttribute("orderId",order.getOrderId());
        model.addAttribute("detail",bookInfos.get(0).getOutline());
        model.addAttribute("send_pay_date",queryResponse.getSendPayDate());
        model.addAttribute("trade_no",queryResponse.getTradeNo());
        model.addAttribute("total_amount",queryResponse.getTotalAmount());
        return "trade_query";
    }

    @RequestMapping("/tradeRefund/{orderId}")
    public String tradeRefund(@PathVariable("orderId") String orderId, Model model, HttpServletResponse response,HttpServletRequest request) throws AlipayApiException {
        BSResult result=orderService.findOrdersByOrderId(orderId);
        Orders order= (Orders) result.getData();
        List<BookInfo> bookInfos=orderDetailService.findBookInfoByOrderId(orderId);
        PayContext payContext=new PayContext();
        payContext.setOrder(order);
        payContext.setBookInfos(bookInfos);
        payContext.setResponse(response);
        BSResult bsResult=alipay.tradeRefund(payContext);

        AlipayTradeRefundResponse refundResponse= (AlipayTradeRefundResponse) bsResult.getData();
        if(refundResponse!=null) {
            String total_amount = refundResponse.getRefundFee();
            model.addAttribute("total_amount", total_amount);
            order.setStatus(5);
            orderService.updateOrders(order);
            return "refund_success";
        }
        else {
            model.addAttribute("exception","refund failed!");
            return "exception";
        }
    }



    @RequestMapping("/refundQuery/{orderId}")
    public String  refundQuery(@PathVariable("orderId") String orderId, Model model, HttpServletResponse response,HttpServletRequest request) throws AlipayApiException {


        BSResult result=orderService.findOrdersByOrderId(orderId);
        Orders order= (Orders) result.getData();
        List<BookInfo> bookInfos=orderDetailService.findBookInfoByOrderId(orderId);
        PayContext payContext=new PayContext();
        payContext.setOrder(order);
        payContext.setBookInfos(bookInfos);
        payContext.setResponse(response);


        BSResult bsResult=alipay.defundQuery(payContext);

        if(bsResult.getCode()==200) {
            AlipayTradeFastpayRefundQueryResponse refundQueryResponse = (AlipayTradeFastpayRefundQueryResponse) bsResult.getData();

            model.addAttribute("total_amount",refundQueryResponse.getRefundAmount());
            model.addAttribute("detail",bookInfos.get(0).getOutline());
            model.addAttribute("send_pay_date",refundQueryResponse.getGmtRefundPay());
            model.addAttribute("trade_no",refundQueryResponse.getTradeNo());

            return "refund_query";
        }else{
            model.addAttribute("exception",bsResult.getMessage());
            return "exception";
        }




    }


}
